package com.shangxia.rachel.common.util.file;

import lombok.extern.slf4j.Slf4j;

import java.io.*;

import java.nio.channels.FileChannel;

import java.nio.file.Files;

import org.apache.commons.io.FileUtils;

/**
 * @ProjectName: rachel
 * @ClassName: FileUtil
 * @Time: 2020/6/11
 * @Author: zy9524
 * @Description: 操作文件
 * @Experience:
 */

@Slf4j
public class FileUtil {
    public static void main(String[] args) throws FileNotFoundException {

    }

    /**
     * 文件复制时推荐使用方法
     *
     * @param source
     * @param dest
     * @throws IOException
     * @Description 复制文件，目标文件存在时会覆盖原文件
     */
    public static void copyFile(File source, File dest) throws IOException {
        try (FileChannel inputChannel = new FileInputStream(source).getChannel();
             FileChannel outputChannel = new FileOutputStream(dest).getChannel();) {
            outputChannel.transferFrom(inputChannel, 0, inputChannel.size());
        } catch (EOFException e) {
            log.error("EOFException{}", e);
        }
    }

    /**
     * 文件复制
     *
     * @param source
     * @param dest
     * @throws IOException
     * @Description:
     */
    public static void copyFileUsingFileStreams(File source, File dest) throws IOException {
        try (InputStream input = new FileInputStream(source);
             OutputStream output = new FileOutputStream(dest);) {
            byte[] buf = new byte[1024];
            int bytesRead;
            while ((bytesRead = input.read(buf)) > 0) {
                output.write(buf, 0, bytesRead);
            }
        } catch (EOFException e) {

        }
    }

    /**
     * 最快
     *
     * @param source
     * @param dest
     * @throws IOException
     */
    public static void copyFileUsingJava7Files(File source, File dest)
            throws IOException {
        Files.copy(source.toPath(), dest.toPath());
    }


    public static String copyFileUsingApacheCommonsIO(File source, File dest)
            throws IOException {
        FileUtils.copyFile(source, dest);
        return "11";
    }
}
